package share

import (
	"oc_saas/glo"
	"oc_saas/model/admin"
	share_req "oc_saas/model/req/share"
	share_res "oc_saas/model/res/share"
	"oc_saas/utils/tool"
)

type Share struct{}

// 用户登录
func (*Share) Login(body *share_req.CommonLogin) string {
	var data *share_res.CommonLogin
	err := glo.OC_DB.
		Model(&admin.User{}).
		Select("oc_user.`username`, oc_user.`password`,oc_user.`only_id`,r.`jwt_expire`,r.`db_id`,t.`db_name`,t.`domain`,a.`application_tag`").
		Joins("LEFT JOIN oc_role as r on r.id = oc_user.role_id").
		Joins("LEFT JOIN oc_tenancy_db as t on t.id = r.db_id").
		Joins("LEFT JOIN oc_application as a on a.id = t.application_id").
		Where("oc_user.`username` = ? AND oc_user.`password` = ?", body.Username, body.Password).
		First(&data).Error
	if err != nil {
		panic(err)
	}
	var baseClaims = new(tool.BaseClaims)
	if data.DBId != 0 { //如果是租户则转换到租户的配置
		baseClaims.DbName = data.DbName
		baseClaims.Domain = data.Domain
		baseClaims.ApplicationTag = data.ApplicationTag
	} else {
		baseClaims.DbName = ""
		baseClaims.Domain = ""
		baseClaims.ApplicationTag = ""
	}
	baseClaims.UUID = data.OnlyID
	// 生成jwt
	j := new(tool.JWTAuth)
	newClaims := j.CreateClaims(*baseClaims, data.JWTExpire)
	token := j.GenTokenString(newClaims)
	return token
}

var ShareService = new(Share)
